import java.util.Random;

/**
 * 加减法口算练习系统 v0.2
 * 新增功能：
 * 1. 显示答案
 * 2. 加法和不超100，减法差不小于0
 * 3. 每行显示多个算式
 */
public class CalculationSystemV02 {

    private static Random random = new Random();

    /**
     * 模块1：生成随机数
     */
    public static int generateRandomNumber(int min, int max) {
        return random.nextInt(max - min + 1) + min;
    }

    /**
     * 模块2：生成带答案的算式
     * @return 包含算式和答案的数组 [算式字符串, 答案]
     */
    public static String[] generateEquationWithAnswer() {
        boolean isAddition = random.nextBoolean();
        int num1, num2, answer;
        String equation;

        if (isAddition) {
            // 加法：确保和不超过100
            num1 = generateRandomNumber(1, 99);
            num2 = generateRandomNumber(1, 100 - num1);
            answer = num1 + num2;
            equation = num1 + " + " + num2 + " = ";
        } else {
            // 减法：确保差不小于0
            num1 = generateRandomNumber(1, 100);
            num2 = generateRandomNumber(1, num1);
            answer = num1 - num2;
            equation = num1 + " - " + num2 + " = ";
        }

        return new String[]{equation, String.valueOf(answer)};
    }

    /**
     * 模块3：格式化输出（每行多个算式）
     */
    public static void printFormattedEquations(String[][] exercises, int problemsPerLine) {
        int totalProblems = exercises.length;

        System.out.println("加减法口算练习系统-v0.2");
        System.out.println("题目：");
        System.out.println("======================");

        // 输出题目
        for (int i = 0; i < totalProblems; i++) {
            System.out.printf("%2d. %-15s", i + 1, exercises[i][0]);

            // 每行指定数量后换行
            if ((i + 1) % problemsPerLine == 0) {
                System.out.println();
            }
        }
        System.out.println("\n");

        // 输出答案
        System.out.println("答案：");
        System.out.println("======================");
        for (int i = 0; i < totalProblems; i++) {
            System.out.printf("%2d. %-15s", i + 1, exercises[i][0] + exercises[i][1]);

            if ((i + 1) % problemsPerLine == 0) {
                System.out.println();
            }
        }
    }

    /**
     * 模块4：生成习题集
     */
    public static void generateExercise(int count, int problemsPerLine) {
        String[][] exercises = new String[count][2]; // [0]=算式, [1]=答案

        for (int i = 0; i < count; i++) {
            exercises[i] = generateEquationWithAnswer();
        }

        printFormattedEquations(exercises, problemsPerLine);
        System.out.println("======================");
        System.out.println("共生成 " + count + " 道题目");
    }

    public static void main(String[] args) {
        generateExercise(50, 4); // 50道题，每行4个
    }
}